<?php
namespace Modules\Groupon\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Groupon\Entities\GrouponRecord;

use Validator;
use ThrowException;
use Auth;

class GrouponRecordController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        $options['with_count'] = ['members'];
        $options['with'] = ['leader.base_user', 'product'];

        $options['only'] = [
            'id',
            'uuid',
            'union_status',
            'union_status_text',
            'need_member',
            'members_count',
            'leader' => [
                'is_leader',
                'base_user' => [
                    'name',
                    'headimg'
                ]
            ],
            'end_at',
            'product',
            'order',
            'created_at'
        ];

        $list = GrouponRecord::getList($options);

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        $record = GrouponRecord::getEntity([
            'uuid' => $uuid,
            'with' => ['members.base_user', 'members.order.sku', 'product']
        ]);

        $info = $record->getInfo([
            'id',
            'uuid',
            'end_at',
            'union_status',
            'union_status_text',
            'product',
            'need_member',
            'members_count',
            'members' => [
                '*' => [
                    'is_leader',
                    'base_user' => [
                        'name',
                        'headimg'
                    ],
                    'order'
                ]
            ]
        ]);

        $order = $record->leader->order;

        $orderSku = $order->sku;
        $sku = $orderSku->base_sku;

        // $info['sku'] = array_merge($sku->getInfo([
        //                 'id',
        //                 'uuid',
        //                 'title',
        //                 'thumb',
        //                 'attrs'
        //             ]), [
        //                 'total' => $orderSku->total,
        //                 'product' => $sku->product->getInfo(['id', 'uuid']),
        //                 'price' => $orderSku->price,
        //                 'selling_price' => $orderSku->selling_price,
        //             ]);

        return [
            'info' => $info
        ];
    }

    public function stat(Request $req, $uuid)
    {
        $stat = [
            'working' => GrouponRecord::status('working')->count(),
            'completed' => GrouponRecord::status('completed')->count(),
            'failed' => GrouponRecord::status('failed')->count(),
        ];

        return [
            'stat' => $stat
        ];
    }
}
